#!/usr/bin/Python
# coding=utf-8
import sys
import os

import traceback
import signal
from thrift.transport import TSocket, TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

sys.path.append('..')
from i_util.thread_pool import ThreadPool
from i_util.input_thread import InputThread
from bdp.i_crawler.i_data_saver import DataSaverService
from bdp.i_crawler.i_data_saver.ttypes import DataSaverRsp
import getopt
import pytoml
from conf import get_config
from i_util.logs import LogHandler
from i_util.ProfilingUtil import profiler_creator
from i_util.ProfilingUtil import profiling_signal_handler

# TODO: 多线程 全都改成 多进程
from i_util.heart_beat import HeartbeatThread
# beanstalk服务的入口
class DataSaverServer(object):
    def __init__(self, conf):
        self.conf = conf
        self.backend={}
        self.backend['server']=self.conf.server
        self.backend['backend'] = self.conf.backend
        self.backend['log']=common.log
        thread_locals = {'processor': (DataSaverProccessor, (common.log, 1)), 'profiler': (profiler_creator, ())}
        self.process_pool = ThreadPool(conf.server['process_thread_num'], thread_locals)
        self.input_thread = InputThread(conf.beanstalk_conf, common.log, self.process_pool);
        self.heartbeat_thread = HeartbeatThread('datasaver', self.backend)
    def start(self):
        self.input_thread.start()
        self.heartbeat_thread.start()
        common.log.info("start DataSaverServer!")
    def stop(self,message):
        self.input_thread.stop()
        common.log.info("stop DataSaverServer %s!" %(message))

# thrift调用的入口
class DataSaverHandler(object):
    def __init__(self):
        self.data_saver = datasaver

    def check_data(self, entity):
        return self.data_saver.check_data(entity)

    def get_schema(self, topic_id):
        return self.data_saver.get_schema(topic_id)

    def reload(self,topic_id=-1):
        # TODO: topic_manager.reload, 各个validator.reload, 各个merger.reload
        data={}
        try:
            common.log.info("start reload topic_id{}".format(topic_id))
            data= self.data_saver.reload(topic_id)
            common.log.info("finash reload topic_id{}".format(topic_id))
        except Exception as e:
            common.log.error("reload fail reason{}".format(e.message))
        return data

def main(conf):
    signal.signal(signal.SIGTERM, signal.SIG_DFL)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    signal.signal(signal.SIGUSR1, lambda a, b: profiling_signal_handler("data_saver", a, b))

    merge_server = DataSaverServer(conf)
    merge_server.start()

    try:
        handler = DataSaverHandler()
        processor = DataSaverService.Processor(handler)
        transport = TSocket.TServerSocket(port=conf.server['port'])
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
        server.setNumThreads(conf.server['server_thread_num'])
        server.serve()
    except Exception, e:
        common.log.error(str(e))
        merge_server.stop("failt")
        os._exit(1)
    merge_server.stop("success")


def usaget():
    pass
if __name__ == '__main__':
    try:
        file_path='./data_saver.toml'
        opt, args = getopt.getopt(sys.argv[1:], 'f:', ['help'])
        for name, value in opt:
            if name == "-f":
                file_path = value
            elif name in ("-h", "--help"):
                usaget()
                sys.exit()
            else:
                assert False, "unhandled option"
        with open(file_path, 'rb') as config:
            config = pytoml.load(config)
        conf = get_config(config)
        import common
        from data_saver import datasaver
        from data_saver_proccessor import DataSaverProccessor

        main(conf)

    except:
        print traceback.format_exc()
